package com.lifeverse.service;

import com.lifeverse.entity.Decision;
import com.lifeverse.service.DecisionEngine.DecisionContext;
import com.lifeverse.service.DecisionEngine.DecisionEvaluation;
import com.lifeverse.service.DecisionEngine.DecisionOption;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 决策评估器
 * 负责评估决策选项的优劣
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DecisionEvaluator {
    
    /**
     * 评估决策选项
     */
    public DecisionEvaluation evaluate(Decision decision, List<DecisionOption> options, DecisionContext context) {
        log.debug("评估决策选项 - 决策ID: {}, 选项数量: {}", decision.getId(), options.size());
        
        DecisionEvaluation evaluation = new DecisionEvaluation();
        Map<String, BigDecimal> optionScores = new HashMap<>();
        
        // 评估每个选项
        for (DecisionOption option : options) {
            BigDecimal score = evaluateOption(option, decision, context);
            optionScores.put(option.getId(), score);
            log.debug("选项评分 - {}: {}", option.getName(), score);
        }
        
        evaluation.setOptionScores(optionScores);
        
        // 找到最高分选项
        String bestOptionId = optionScores.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse(options.get(0).getId());
        
        DecisionOption bestOption = options.stream()
                .filter(opt -> opt.getId().equals(bestOptionId))
                .findFirst()
                .orElse(options.get(0));
        
        // 生成评估理由
        String reasoning = generateReasoning(bestOption, optionScores, context);
        evaluation.setReasoning(reasoning);
        
        // 计算置信度
        BigDecimal confidence = calculateConfidence(optionScores, context);
        evaluation.setConfidence(confidence);
        
        log.debug("决策评估完成 - 最佳选项: {}, 置信度: {}", bestOption.getName(), confidence);
        
        return evaluation;
    }
    
    /**
     * 评估单个选项
     */
    private BigDecimal evaluateOption(DecisionOption option, Decision decision, DecisionContext context) {
        BigDecimal score = BigDecimal.ZERO;
        
        // 基础分数
        score = score.add(BigDecimal.valueOf(50));
        
        // 根据选项来源调整分数
        score = score.add(evaluateBySource(option));
        
        // 根据生命体特征调整分数
        score = score.add(evaluateByLifeEntityCharacteristics(option, decision, context));
        
        // 根据历史成功率调整分数
        score = score.add(evaluateByHistoricalSuccess(option, decision, context));
        
        // 根据风险评估调整分数
        score = score.add(evaluateRisk(option, decision, context));
        
        // 根据资源需求调整分数
        score = score.add(evaluateResourceRequirement(option, decision, context));
        
        // 根据预期影响调整分数
        score = score.add(evaluateExpectedImpact(option, decision, context));
        
        // 确保分数在合理范围内
        return score.max(BigDecimal.ZERO).min(BigDecimal.valueOf(100));
    }
    
    /**
     * 根据选项来源评估
     */
    private BigDecimal evaluateBySource(DecisionOption option) {
        switch (option.getSource()) {
            case "RULE":
                return BigDecimal.valueOf(20); // 基于规则的选项较可靠
            case "HISTORY":
                return BigDecimal.valueOf(15); // 历史经验有一定参考价值
            case "INNOVATION":
                return BigDecimal.valueOf(10); // 创新选项有潜力但风险较高
            case "DEFAULT":
                return BigDecimal.valueOf(5);  // 默认选项保守但安全
            default:
                return BigDecimal.ZERO;
        }
    }
    
    /**
     * 根据生命体特征评估
     */
    private BigDecimal evaluateByLifeEntityCharacteristics(DecisionOption option, Decision decision, DecisionContext context) {
        BigDecimal score = BigDecimal.ZERO;
        
        // 根据生命体的智慧值调整
        BigDecimal wisdomScore = decision.getLifeEntity().getWisdomScore();
        if (wisdomScore.compareTo(BigDecimal.valueOf(500)) > 0) {
            score = score.add(BigDecimal.valueOf(5)); // 高智慧生命体的选择更可靠
        }
        
        // 根据生命体的创造力调整
        BigDecimal creativityScore = decision.getLifeEntity().getCreativityScore();
        if ("INNOVATION".equals(option.getSource()) && creativityScore.compareTo(BigDecimal.valueOf(70)) > 0) {
            score = score.add(BigDecimal.valueOf(10)); // 高创造力生命体适合创新选项
        }
        
        // 根据生命体的协作能力调整
        BigDecimal collaborationScore = decision.getLifeEntity().getCollaborationScore();
        if (decision.getType().name().contains("COLLABORATION") && 
            collaborationScore.compareTo(BigDecimal.valueOf(70)) > 0) {
            score = score.add(BigDecimal.valueOf(8)); // 高协作能力适合协作决策
        }
        
        return score;
    }
    
    /**
     * 根据历史成功率评估
     */
    private BigDecimal evaluateByHistoricalSuccess(DecisionOption option, Decision decision, DecisionContext context) {
        // 这里应该查询类似决策的历史成功率
        // 简化实现，返回基于选项来源的估计成功率
        switch (option.getSource()) {
            case "RULE":
                return BigDecimal.valueOf(12); // 规则通常有较高成功率
            case "HISTORY":
                return BigDecimal.valueOf(10); // 历史成功的方案有一定成功率
            case "INNOVATION":
                return BigDecimal.valueOf(5);  // 创新方案成功率不确定
            case "DEFAULT":
                return BigDecimal.valueOf(8);  // 默认方案成功率中等
            default:
                return BigDecimal.valueOf(3);
        }
    }
    
    /**
     * 评估风险
     */
    private BigDecimal evaluateRisk(DecisionOption option, Decision decision, DecisionContext context) {
        BigDecimal riskScore = BigDecimal.ZERO;
        
        // 根据选项来源评估风险
        switch (option.getSource()) {
            case "INNOVATION":
                riskScore = riskScore.subtract(BigDecimal.valueOf(8)); // 创新选项风险较高
                break;
            case "DEFAULT":
                riskScore = riskScore.add(BigDecimal.valueOf(5)); // 默认选项风险较低
                break;
            case "RULE":
                riskScore = riskScore.add(BigDecimal.valueOf(3)); // 规则选项风险中等
                break;
        }
        
        // 根据生命体健康状况评估风险承受能力
        BigDecimal healthScore = decision.getLifeEntity().getHealthScore();
        if (healthScore.compareTo(BigDecimal.valueOf(80)) > 0) {
            riskScore = riskScore.add(BigDecimal.valueOf(3)); // 健康状况好，可承受更多风险
        } else if (healthScore.compareTo(BigDecimal.valueOf(50)) < 0) {
            riskScore = riskScore.subtract(BigDecimal.valueOf(5)); // 健康状况差，应避免风险
        }
        
        return riskScore;
    }
    
    /**
     * 评估资源需求
     */
    private BigDecimal evaluateResourceRequirement(DecisionOption option, Decision decision, DecisionContext context) {
        BigDecimal resourceScore = BigDecimal.ZERO;
        
        // 根据生命体能量水平评估资源可用性
        BigDecimal energyLevel = decision.getLifeEntity().getEnergyLevel();
        
        if (energyLevel.compareTo(BigDecimal.valueOf(80)) > 0) {
            resourceScore = resourceScore.add(BigDecimal.valueOf(8)); // 能量充足，可执行复杂选项
        } else if (energyLevel.compareTo(BigDecimal.valueOf(30)) < 0) {
            resourceScore = resourceScore.subtract(BigDecimal.valueOf(10)); // 能量不足，应选择简单选项
        }
        
        // 根据选项复杂度调整（简化评估）
        if ("INNOVATION".equals(option.getSource())) {
            resourceScore = resourceScore.subtract(BigDecimal.valueOf(5)); // 创新选项通常需要更多资源
        } else if ("DEFAULT".equals(option.getSource())) {
            resourceScore = resourceScore.add(BigDecimal.valueOf(3)); // 默认选项资源需求较少
        }
        
        return resourceScore;
    }
    
    /**
     * 评估预期影响
     */
    private BigDecimal evaluateExpectedImpact(DecisionOption option, Decision decision, DecisionContext context) {
        BigDecimal impactScore = BigDecimal.ZERO;
        
        // 根据决策类型评估预期影响
        switch (decision.getType()) {
            case RESOURCE_ALLOCATION:
                if ("RULE".equals(option.getSource())) {
                    impactScore = impactScore.add(BigDecimal.valueOf(10)); // 规则化资源分配效果好
                }
                break;
            case COLLABORATION:
                if (decision.getLifeEntity().getCollaborationScore().compareTo(BigDecimal.valueOf(70)) > 0) {
                    impactScore = impactScore.add(BigDecimal.valueOf(8)); // 高协作能力影响大
                }
                break;
            case EVOLUTION:
                if ("INNOVATION".equals(option.getSource())) {
                    impactScore = impactScore.add(BigDecimal.valueOf(12)); // 创新对进化影响大
                }
                break;
            default:
                impactScore = impactScore.add(BigDecimal.valueOf(5)); // 默认影响
        }
        
        return impactScore;
    }
    
    /**
     * 生成评估理由
     */
    private String generateReasoning(DecisionOption bestOption, Map<String, BigDecimal> optionScores, 
                                   DecisionContext context) {
        StringBuilder reasoning = new StringBuilder();
        
        reasoning.append("选择方案: ").append(bestOption.getName()).append("\n");
        reasoning.append("评分: ").append(optionScores.get(bestOption.getId())).append("\n");
        reasoning.append("选择理由:\n");
        
        // 根据选项来源生成理由
        switch (bestOption.getSource()) {
            case "RULE":
                reasoning.append("- 基于系统规则，具有较高可靠性\n");
                break;
            case "HISTORY":
                reasoning.append("- 基于历史成功经验，有实践验证\n");
                break;
            case "INNOVATION":
                reasoning.append("- 创新方案，具有突破性潜力\n");
                break;
            case "DEFAULT":
                reasoning.append("- 保守方案，风险较低\n");
                break;
        }
        
        // 根据生命体特征生成理由
        if (context.getLifeEntity().getWisdomScore().compareTo(BigDecimal.valueOf(500)) > 0) {
            reasoning.append("- 生命体智慧水平较高，适合执行复杂决策\n");
        }
        
        if (context.getLifeEntity().getEnergyLevel().compareTo(BigDecimal.valueOf(80)) > 0) {
            reasoning.append("- 生命体能量充足，可支持决策执行\n");
        }
        
        return reasoning.toString();
    }
    
    /**
     * 计算置信度
     */
    private BigDecimal calculateConfidence(Map<String, BigDecimal> optionScores, DecisionContext context) {
        if (optionScores.isEmpty()) {
            return BigDecimal.valueOf(0.5);
        }
        
        // 获取最高分和次高分
        List<BigDecimal> sortedScores = optionScores.values().stream()
                .sorted((a, b) -> b.compareTo(a))
                .toList();
        
        BigDecimal highestScore = sortedScores.get(0);
        BigDecimal secondHighestScore = sortedScores.size() > 1 ? sortedScores.get(1) : BigDecimal.ZERO;
        
        // 计算分数差距
        BigDecimal scoreDifference = highestScore.subtract(secondHighestScore);
        
        // 基础置信度
        BigDecimal baseConfidence = BigDecimal.valueOf(0.6);
        
        // 根据分数差距调整置信度
        BigDecimal confidenceAdjustment = scoreDifference.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
        BigDecimal confidence = baseConfidence.add(confidenceAdjustment);
        
        // 根据生命体智慧水平调整置信度
        BigDecimal wisdomScore = context.getLifeEntity().getWisdomScore();
        if (wisdomScore.compareTo(BigDecimal.valueOf(700)) > 0) {
            confidence = confidence.add(BigDecimal.valueOf(0.1));
        } else if (wisdomScore.compareTo(BigDecimal.valueOf(300)) < 0) {
            confidence = confidence.subtract(BigDecimal.valueOf(0.1));
        }
        
        // 确保置信度在合理范围内
        return confidence.max(BigDecimal.valueOf(0.1)).min(BigDecimal.valueOf(1.0));
    }
}